package com.huika.dealontop.control.homepage.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.view.AutoScrollViewPager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.JsonToken;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.homepage.CaiLuUtils.Number.NumberFormat;
import com.huika.dealontop.control.homepage.Interface.StopRefreshInterface;
import com.huika.dealontop.control.homepage.activity.DindanActivity;
import com.huika.dealontop.control.homepage.activity.SearchActivity;
import com.huika.dealontop.control.homepage.database.DindanDbHelper;
import com.huika.dealontop.control.homepage.utils.cartproductnumber.CartProductNumber;
import com.huika.dealontop.control.homepage.utils.fourad.fouradfactory.FourAdFactory;
import com.huika.dealontop.control.main.MainActivity;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.nearby.adapter.NearbyGrouponAdapterTwo;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.control.timelimit.activity.ShoppingCartAtc;
import com.huika.dealontop.control.timelimit.fragment.ShoppingCartFragment;
import com.huika.dealontop.support.domain.AdvertisementInfo;
import com.huika.dealontop.support.domain.DindanBean;
import com.huika.dealontop.support.domain.HomePageAdvertisementSeatInfo;
import com.huika.dealontop.support.domain.HomePageIconInfo;
import com.huika.dealontop.support.domain.HomePageLimitTimeInfo;
import com.huika.dealontop.support.domain.LocationBean;
import com.huika.dealontop.support.domain.NearbyGrouponBean;
import com.huika.dealontop.support.event.SelectShoppingCarEvent;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.ServerFlagError;
import com.huika.dealontop.utils.DebugTool;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.GaodeMapUtil;
import com.huika.dealontop.utils.JpushUtil;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.webview.BaseWebViewAct;
import com.huika.huikalib.utils.MoneyShowTool;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.util.JLogger;
import de.greenrobot.event.EventBus;

//, BaseFra.OnInitShowListener
public class HomePageFragment extends BaseFra implements StopRefreshInterface, PullToRefreshBase.InnerPullToRefresh,
        GMapUtil.MyLocationListener {
    private AutoScrollViewPager<AdvertisementInfo> mAutoScrollViewPager;
    private View mParentView;
    private ViewPager mIconViewPger;
    private PullToRefreshListView mPullToRefreshListView;
    private ImageView mFab;
    private LinearLayout mSearchbarbackground;
    private LinearLayout mSearchbar;
    private Animation mAniOut;
    private Animation mFabAniOut;
    private Animation.AnimationListener mAniatonlistener1In;
    private Animation.AnimationListener mAniatonlistener1Out;
    private Animation mSearchbarAniIn;
    private Animation mFabAniIn;
    private ArrayList<AdvertisementInfo> mAdvertisementInfoLists = new ArrayList<AdvertisementInfo>();
    private ArrayList<HomePageIconInfo> mHomePageIconInfoLists = new ArrayList<HomePageIconInfo>();

    private HomePageLimitTimeInfo mLitmit = new HomePageLimitTimeInfo();
    private ImageView mCoverIv;
    private MyPagerAdapter mHomepageIconAdapter;
    private TextView mLimtTime;
    private TextView mBuyLimitName;
    private TextView mSalePrice;
    private TextView mDiscount;
    private NearbyGrouponAdapterTwo nearbyGrouponAdapter;
    private JSONWrapAjaxParams ajaxParams;
    private FormResultRequest<List<NearbyGrouponBean>> request;
    private List<NearbyGrouponBean> NearbyGrouponList = new ArrayList<NearbyGrouponBean>();
    private LinearLayout mNearBy;
    private LinearLayout mIconDotContainer;
    private TextView mHomepage_searchbar;
    private int mTotalFlag = 1;
    private long mLimttimeDateEnd;
    private RelativeLayout rlyt_limitimeshop;
    private GMapUtil gMapUtil;
    private TextView homepage_tv_refresh_position;
    private ImageView homepage_iv_refresh;
    private Animation mSearchBackGroundOut;
    private Animation mSearchBackGroundIn;
    private MainActivity mMainActivity;
    //极光推送参数
    public static boolean isForeground = false;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String MESSAGE_RECEIVED_CARTPRODUCTNUMBER = "com.huika.dealontop.control.homepage.fragment_CARTPRODUCTNUMBER";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_CARTPRODUCTNUMBER = "cartNumber";
    public static final String KEY_EXTRAS = "extras";
    private RelativeLayout mDinDanContainer;
    private static TextView mDinDanNumber;
    private CountDownTimer mAutoTime;
    private long mLimttimeDateStart;
    private long mLimttimeDate;

    private GaodeMapUtil gaodeMapHelper;
    public LocationBean mLocationBean;
    private String lng;
    private String lat;
    private ImageView mIvBackToTop;
    private static TextView mIvCartProductNumber;
    private LinearLayout mFourAdContainer;
    private LinearLayout mFourAdContainerTwo;
    private ListView mRefreshableView;
    private View mHeadView;
    private RelativeLayout mCartProductContainer;
    private LinearLayout mHomePageScrollViewPageContainer;
    private int mVisibleItemCount = 0;


    public HomePageFragment() {
        super();
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View homePageView = inflater.inflate(R.layout.frag_homepage, container, false);
        //初始化EventBus
        EventBus.getDefault().register(this);
        return homePageView;
    }

    @Override
    protected void initWidget(View parentView) {
        Log.e("OK", JPushInterface.getRegistrationID(getActivity()) + "");
        super.initWidget(parentView);
        mMainActivity = (MainActivity) getActivity();
        mParentView = parentView;
        initPullToRefreshListView();
        mHomepage_searchbar = (TextView) parentView.findViewById(R.id.homepage_searchbar);
        mIconViewPger = (ViewPager) mHeadView.findViewById(R.id.icon_viewpager);
        mSearchbarbackground = (LinearLayout) parentView.findViewById(R.id.ll_homepage_searchbar_background);
        mSearchbar = (LinearLayout) parentView.findViewById(R.id.ll_homepage_searchbar);
        mNearBy = (LinearLayout) mHeadView.findViewById(R.id.homepage_nearbyBuy);
        mIvBackToTop = (ImageView) parentView.findViewById(R.id.iv_back_to_top);
        mIvCartProductNumber = (TextView) parentView.findViewById(R.id.homepage_cartProductNumber);
        mCartProductContainer = (RelativeLayout) parentView.findViewById(R.id.homepage_cartProduct_container);
        mIconDotContainer = (LinearLayout) parentView.findViewById(R.id.homepage_dotContainer);

        initDinDangView();

        initFloatingActionButton();
        initAutoScrollViewPage();
        initHomePageIconViewPage();
        initLimitTimeView();
        initFourAdvertisementView();
        initAnimation();
        initNearbyGrouponView();
        initLocationView();
        initListener();
        initGMap();
        //获取到坐标位置，并访问网络去刷新listview
        getLatestNearByData();
        //获取到坐标位置并显示在文本中。
        UIUtils.postDelayed(new Runnable() {
            @Override
            public void run() {
                initLib();
            }
        }, 1000);
    }

    //从购物车每次更新中发送的eventBus

    public void onEventMainThread(SelectShoppingCarEvent event) {
        if (GlobalApp.getUserModel() != null)
            new CartProductNumber(context, GlobalApp.getUserModel().getUserID() + "");
    }

    private void initLib() {
        //登入成功后加载用户车资料
        if (GlobalApp.getUserModel() != null) {
            new CartProductNumber(context, GlobalApp.getUserModel().getUserID() + "");
        }
    }


    public static void initCartProduct(int cartProductNumber) {
        if (mIvCartProductNumber == null) {
            return;
        }

        if (cartProductNumber == 0) {
            mIvCartProductNumber.setVisibility(View.INVISIBLE);
        } else {
            if (cartProductNumber > 9) {
                mIvCartProductNumber.setBackgroundResource(R.mipmap.homepage_dindan_dottwo);
            } else if (cartProductNumber <= 9) {
                mIvCartProductNumber.setBackgroundResource(R.mipmap.homepage_dindan_dotone);
            }
            mIvCartProductNumber.setText(cartProductNumber + "");
            mIvCartProductNumber.setVisibility(View.VISIBLE);
        }
    }

    private void initGMap() {
        gMapUtil = new GMapUtil(getActivity(), this);
        gMapUtil.getLatestGeoAddress();
        gMapUtil.setStopRefreshAnim(this);

    }


    private void initDinDangView() {
        //TODO
        mDinDanContainer = (RelativeLayout) mParentView.findViewById(R.id.homepage_rl_dindan_container);
        mDinDanNumber = (TextView) mParentView.findViewById(R.id.homepage_tv_dindan_number);
        recevierFromNet();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (MESSAGE_RECEIVED_CARTPRODUCTNUMBER.equals(intent.getAction())) {
                int number = intent.getIntExtra(KEY_CARTPRODUCTNUMBER, 0);
                //设置首页的数量
                initCartProduct(number);
                //设置主页购物车的数量
                MainActivity.initCartProduct(number);
            }
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!JpushUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }

                try {
                    Gson gson = new Gson();
                    DindanBean dindanBean = gson.fromJson(extras, DindanBean.class);
                    long times = System.currentTimeMillis();

                    String productImageUrl = dindanBean.getProductImageUrl();
                    String productId = dindanBean.getProductId();
                    String productName = dindanBean.getProductName();

                    //最后一个参数为0,因为0是假,0代表着没有阅读的新消息
                    new DindanDbHelper().setContent(times, productImageUrl, productName, productId, 1);
                } catch (Exception e) {
                    //showToastMsg(e.toString());
                }
                recevierFromNet();
                //当每次收到信息的时候,我都去服务器请求最新的数据
            }
        }
    }

    public static void recevierFromNet() {
        if (mDinDanNumber == null) {
            return;
        }
        int countNum = new DindanDbHelper().getUnUsedableCountNum();
        if (countNum == 0) {
            mDinDanNumber.setVisibility(View.INVISIBLE);
        } else {
            if (countNum > 9) {
                mDinDanNumber.setBackgroundResource(R.mipmap.homepage_dindan_dottwo);
            } else if (countNum <= 9) {
                mDinDanNumber.setBackgroundResource(R.mipmap.homepage_dindan_dotone);
            }
            mDinDanNumber.setText(countNum + "");
            mDinDanNumber.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        isForeground = true;
        super.onResume();
        //点击进入页面，会重新刷新下数据。
    }


    @Override
    public void onPause() {
        isForeground = false;
        super.onPause();
    }


    private void initLocationView() {
        homepage_iv_refresh = (ImageView) mParentView.findViewById(R.id.homepage_iv_refresh);
        homepage_tv_refresh_position = (TextView) mParentView.findViewById(R.id.homepage_tv_refresh_position);


    }


    @Override
    protected void initData() {
        super.initData();

        lng = PreferencesHelper.getInstance().getString(PreferencesHelper.CURRENT_LOCATION_LNG);
        lat = PreferencesHelper.getInstance().getString(PreferencesHelper.CURRENT_LOCATION_LAT);

    }

    //初始化为7；
    private int mSort = 7;
    private Response.Listener<RequestResult<List<NearbyGrouponBean>>> GetNearbyGrouponPro = new
            Response.Listener<RequestResult<List<NearbyGrouponBean>>>() {
                @Override
                public void onResponse(RequestResult<List<NearbyGrouponBean>> Result) {
                    final int totalSize = Result.getTotalSize();
                    mSort = Result.getSort();
                    if (Result.flag == 1) {
                        if (Result != null && Result.getRs() != null) {

                            //无数据
                            if (CURRENT_PAGE == 1) {
                                NearbyGrouponList = Result.getRs();
                            } else {
                                NearbyGrouponList.addAll(Result.getRs());
                            }

                            nearbyGrouponAdapter.setGroup(NearbyGrouponList);
                        }
                        mPullToRefreshListView.onRefreshComplete();
                        if (NearbyGrouponList.size() >= totalSize) {// 无记录
                            mPullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        } else {
                            if (mPullToRefreshListView.getMode() == PullToRefreshBase.Mode.PULL_FROM_START)
                                mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                        }

                        //数据为0，团购列表为0.
                        if (NearbyGrouponList.size() <= 0) {
                            mNearBy.setVisibility(View.GONE);
                        }

                        //setListViewHeightBasedOnChildren(mListView);

                    }

                }
            };

    /*用来解决scrollview加载listview的测量子孩子的问题*/
    private void setListViewHeightBasedOnChildren(LinearLayout ll) {
//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null) {
//            // pre-condition
//            return;
//        }

        int totalHeight = 0;
        for (int i = 0; i < ll.getChildCount(); i++) {
            View item = ll.getChildAt(i);

            item.measure(0, 0);
            totalHeight += item.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = ll.getLayoutParams();
        params.height = totalHeight;
        ll.setLayoutParams(params);
    }

    private void initNearbyGrouponView() {

        nearbyGrouponAdapter = new NearbyGrouponAdapterTwo(UIUtils.getContext());
        mRefreshableView.setAdapter(nearbyGrouponAdapter);
        mPullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String couMerID = NearbyGrouponList.get(position - 2).getCouMerID();
                String couMerImage = NearbyGrouponList.get(position - 2).getCouMerImage();
                Intent intent = new Intent(getActivity(), ProductDetailsActivity1.class);
                intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, couMerImage);
                intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, couMerID);
                showActivity(getActivity(), intent);
            }
        });
    }

    private void getLatestNearByData() {
        int sortnum = mSort;
        CURRENT_PAGE = 1;

        ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("longitudeX", lng);//经度
        ajaxParams.putCommonTypeParam("dimensionsY", lat);//维度
        ajaxParams.putCommonTypeParam("nearByAreaId", 0);//附近地区名称(默认值0，所有地区商品)
        ajaxParams.putCommonTypeParam("categoryId", 0);//分类名称(默认值0，所有分类商品)
        ajaxParams.putCommonTypeParam("sort", sortnum);//排序
        ajaxParams.putCommonTypeParam("isForHomeDelivery", 0);//0、表示所有  1、表示上门
        ajaxParams.putCommonTypeParam("isForOrder", 0);//0、表示所有  1、表示免预约
        ajaxParams.putCommonTypeParam("isForLimitRule", 0);//0、表示所有  1、表示免预约
        // ajaxParams.putCommonTypeParam("pageNo", 1);//分页码

        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);//分页大小
        //showToastMsg(lng + ">>>" + lat);
        request = new FormResultRequest<List<NearbyGrouponBean>>
                (UrlConstants
                        .NEARBYGROUPON, GetNearbyGrouponPro, this, new
                        TypeToken<RequestResult<List<NearbyGrouponBean>>>() {
                        }.getType());
        request.setRequestParams(ajaxParams);
        executeGetNearbyGrouponPro();

    }


    /**
     * 获取身边(附近)团购
     */
    private void executeGetNearbyGrouponPro() {

        // 刷新
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        executeRequest(request);
    }


    private void initFourAdvertisementView() {
        mFourAdContainer = (LinearLayout) mHeadView.findViewById(R.id.homepage_fouradvertisement_container);
        mFourAdContainerTwo = (LinearLayout) mHeadView.findViewById(R.id.homepage_fouradvertisement_containerTwo);

        fourAdvertisementFromNet();
    }


    private void fourAdvertisementFromNet() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        FormResultRequest<ArrayList<HomePageAdvertisementSeatInfo>> loginRequest = new FormResultRequest(UrlConstants
                .FOURADVERTISEMENT, getFourAdvertisementListener, this,
                new TypeToken<RequestResult<ArrayList<HomePageAdvertisementSeatInfo>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        executeRequest(loginRequest);
    }


    private Response.Listener<RequestResult<ArrayList<HomePageAdvertisementSeatInfo>>> getFourAdvertisementListener =
            new Response.Listener<RequestResult<ArrayList<HomePageAdvertisementSeatInfo>>>() {

                @Override
                public void onResponse(RequestResult<ArrayList<HomePageAdvertisementSeatInfo>> result) {
                    DebugTool.i("HomeAppIcon", "");
                    if (result != null && result.flag == 1) {
                        ArrayList<HomePageAdvertisementSeatInfo> rs = result.getRs();
                        ArrayList<HomePageAdvertisementSeatInfo> banner = result.getBanner();
                        View view = null;
                        //initHomePageFourAdvertisementDatas();
                        mFourAdContainer.removeAllViews();
                        if (rs.size() != 0) {
                            view = new FourAdFactory(HomePageFragment.this.getActivity(), rs).selectAdView();
                            mFourAdContainer.addView(view);
                        }

                        mFourAdContainerTwo.removeAllViews();
                        //
                        if (banner != null && banner.size() != 0) {
                            //mFourAdContainerTwo.setVisibility(View.VISIBLE);
                            view = new FourAdFactory(HomePageFragment.this.getActivity(), banner).selectAdView();
                            mFourAdContainerTwo.addView(view);
                            //mFourAdContainerTwo.set
                        }
                        //setListViewHeightBasedOnChildren(mFourAdContainer);

                        totalFlag();
                    }
                }
            };


    private void initLimitTimeView() {
        mLimtTime = (TextView) mHeadView.findViewById(R.id.homepage_limittimeshop);
        mBuyLimitName = (TextView) mHeadView.findViewById(R.id.homepage_buylimtname);
        mSalePrice = (TextView) mHeadView.findViewById(R.id.homepage_salePrice);
        mDiscount = (TextView) mHeadView.findViewById(R.id.homepage_limittime_discount);
        rlyt_limitimeshop = (RelativeLayout) mHeadView.findViewById(R.id.rlyt_limitimeshop);
        limitTimefromNet();
    }

    private void initHomeBuyLimitInfoDatas() {
        if (mLitmit.getEndTime() == null) {
            return;
        }
        mLimttimeDateEnd = Long.parseLong(mLitmit.getEndTime());

        mLimttimeDateStart = Long.parseLong(mLitmit.getSysTime());
        mLimttimeDate = mLimttimeDateEnd - mLimttimeDateStart;
        //mLimtTime.setText(DateTimeTool.dhmsDate(mLimttimeDate));
        mBuyLimitName.setText(mLitmit.getBuyLimitName());
        mSalePrice.setText(MoneyShowTool.nolastDFStr(mLitmit.getSalePrice()));

        mDiscount.setText(MoneyShowTool.nolastDFStr(mLitmit.getDiscount()) + "% Off");
        if (mLimttimeDate <= 0) {
            rlyt_limitimeshop.setVisibility(View.GONE);
        }
        if (mAutoTime != null) {
            mAutoTime.cancel();
        }
        DebugTool.i("abc", mLitmit.getEndTime() + "");
        mAutoTime = new CountDownTimer(mLimttimeDate, 1000) {
            public void onTick(long mLimttimeDate) {
                mLimtTime.setText(NumberFormat.getCountdownTimeHMS(mLimttimeDate / 1000));
            }

            public void onFinish() {
                //todo
            }
        }.start();
    }

    private void limitTimefromNet() {
        //Home/HomeBuyLimit
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        //ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));
        FormResultRequest<HomePageLimitTimeInfo> loginRequest = new FormResultRequest(UrlConstants.HOMEBUYLIMIT,
                getHomeBuyLimitInfo, this,
                new TypeToken<RequestResult<HomePageLimitTimeInfo>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        executeRequest(loginRequest);
    }


    private Response.Listener<RequestResult<HomePageLimitTimeInfo>> getHomeBuyLimitInfo = new Response
            .Listener<RequestResult<HomePageLimitTimeInfo>>() {

        @Override
        public void onResponse(RequestResult<HomePageLimitTimeInfo> result) {
            DebugTool.i("getHomeBuyLimitInfo", "");
            if (result != null && result.flag == 1) {
                mLitmit = result.getRs();

                initHomeBuyLimitInfoDatas();
                totalFlag();
            }
        }
    };


    //经过透明度计算值为350
    public void setSearchbarAlpha(int value) {

        //使透明横条达到替换内容
        if (mSearchbarbackground.getVisibility() != View.GONE) {
            mSearchbarbackground.setAlpha(1.0f + (value / 350.0f));
            if (changeAnimationInnerflag) {
                mSearchbar.setAlpha(1.0f + (value / 350.0f));
            }
            if (value < 0) {
                mVisibleItemCount = 1;
               // Homepage_floatingactionbutton_animation();
                handler.sendMessageDelayed(handler.obtainMessage(),10);
            }
        }
    }

    boolean changeAnimationInnerflag = true;
    boolean setAnimationflag = true;

    private void initAnimation() {
        //消失动画
        mFabAniIn = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_searchbar_alpha_in);
        mSearchbarAniIn = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_searchbar_alpha_in);
        mSearchBackGroundIn = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_searchbarbackground_alpha_in);
        mSearchBackGroundOut = AnimationUtils.loadAnimation(getActivity(), R.anim
                .homepage_searchbarbackground_alpha_out);
        //显现动画
        mAniOut = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_searchbar_alpha_out);
        mFabAniOut = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_searchtool_drag_out);
        mAniatonlistener1In = new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (setAnimationflag) {

                    mFab.setVisibility(View.GONE);

                    mFab.setClickable(false);
                    //mDinDanContainer.setOnClickListener(HomePageFragment.this);
                    mSearchbar.startAnimation(mAniOut);
                } else {

                    mFab.setOnClickListener(HomePageFragment.this);
                    //mDinDanContainer.setOnClickListener(null);
                    mSearchbar.setVisibility(View.GONE);
                    mSearchbarbackground.setVisibility(View.GONE);
                    mHomepage_searchbar.setVisibility(View.GONE);
                    mFab.startAnimation(mFabAniOut);
                }
                setSearchbarAlpha(0);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        };
        mAniatonlistener1Out = new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //mSearchbarbackground.setBackgroundResource(R.mipmap.homepage_searbar_backgroundtwo);
                if (setAnimationflag) {
                    mHomepage_searchbar.setVisibility(View.VISIBLE);
                }


            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (setAnimationflag) {
                    mSearchbar.setVisibility(View.VISIBLE);
                    mSearchbarbackground.setVisibility(View.VISIBLE);
                    mHomepage_searchbar.setVisibility(View.VISIBLE);
                    //mDinDanContainer.setVisibility(View.VISIBLE);
                    //mDinDanContainer.setOnClickListener(HomePageFragment.this);
                } else {
                    mFab.setVisibility(View.VISIBLE);
                }
                changeAnimationInnerflag = true;
                setSearchbarAlpha(0);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        };
        mFabAniIn.setAnimationListener(mAniatonlistener1In);
        mSearchbarAniIn.setAnimationListener(mAniatonlistener1In);
        mSearchBackGroundIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mSearchbarbackground.startAnimation(mSearchBackGroundOut);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        mAniOut.setAnimationListener(mAniatonlistener1Out);
        mFabAniOut.setAnimationListener(mAniatonlistener1Out);
        mSearchBackGroundOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
//                mSearchbarbackground.setVisibility(View.INVISIBLE);
                if (setAnimationflag) {
                    mSearchbarbackground.setBackgroundResource(R.mipmap.homepage_searchbar_backgroundone);
                } else {
                    mSearchbarbackground.setBackgroundResource(R.mipmap.homepage_searchbar_backgroundtwo);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // mSearchbarbackground.setVisibility(View.VISIBLE );

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //TODO
        //开始的时候物体都出现了.
        mFab.setAnimation(mFabAniIn);
        mSearchbar.setAnimation(mSearchbarAniIn);
    }

    public void changeAnimation() {
        if (changeAnimationInnerflag) {
            changeAnimationInnerflag = false;
            //true的时候圆球消失，收搜框显现，
            //false的时候相反
            //第一次加载页面的时候flag为flase
            if (setAnimationflag) {
                mFab.startAnimation(mFabAniIn);
                mSearchbarbackground.startAnimation(mSearchBackGroundIn);
            } else {
                mSearchbar.startAnimation(mSearchbarAniIn);
                mSearchbarbackground.startAnimation(mSearchBackGroundIn);
            }
        }
    }


    private void initPullToRefreshListView() {
        mPullToRefreshListView = (PullToRefreshListView) mParentView.findViewById(R.id
                .homepage_PullToRefreshListView);
        //mPullToRefreshScrollView.setFilterTouchEvents(true);
        mHeadView = View.inflate(context, R.layout.frag_homepage_include_piece, null);
        mRefreshableView = mPullToRefreshListView.getlv();
        mRefreshableView.addHeaderView(mHeadView);

        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //写1个flag每次成功了就将这个flag向右移一位,直到移动了5位才应许刷新成功.100000 也就是32为成功.
                mTotalFlag = 1;
                //轮播图的刷新
                AdvertisementFromNet();
                //HomepageIncon的刷新
                //AppIconFromNet();
                //限时抢购的刷新
                limitTimefromNet();
                //4个广告位的刷新
                fourAdvertisementFromNet();
                //刷新附近的内容.
                CURRENT_PAGE = 1;
                mSort = 7;
                //更新图标
                AppIconFromNet();

                getLatestNearByData();
                executeGetNearbyGrouponPro();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                CURRENT_PAGE++;
                // 加载下一页
                //ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
                //executeRequest(request);
                executeGetNearbyGrouponPro();
            }
        });

        mPullToRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mVisibleItemCount = visibleItemCount;

                handler.sendMessageDelayed(handler.obtainMessage(),10);

            }
        });

    }

    private void Homepage_floatingactionbutton_animation() {
        if (changeAnimationInnerflag) {
            if (mVisibleItemCount > 3 && flagDown && (mFab.getVisibility() == View.GONE)) {
                flagDown = false;
                flagUp = true;
                //false显示的是球已经开始啦.
                setAnimationflag = false;
                changeAnimation();
                mIvBackToTop.setVisibility(View.VISIBLE);
            } else if (mVisibleItemCount <= 3 && flagUp && (mSearchbar.getVisibility() == View.GONE)) {
                flagUp = false;
                flagDown = true;
                //
                setAnimationflag = true;
                changeAnimation();
                mIvBackToTop.setVisibility(View.GONE);
            }

        }
    }

    boolean flagUp = false;
    boolean flagDown = true;

    /**
     * 用于用户手指离开MyScrollView的时候获取MyScrollView滚动的Y距离，然后回调给onScroll方法中
     */
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            Homepage_floatingactionbutton_animation();
//            scrollY = mPullToRefreshListView.getRefreshableView().getScrollY();
//           // showToastMsg("这里会走吗"+scrollY);
//            if (changeAnimationInnerflag) {
//                if (scrollY > 400 && flagDown && (mFab.getVisibility() == View.GONE)) {
//                    flagDown = false;
//                    flagUp = true;
//                    //false显示的是球已经开始啦.
//                    setAnimationflag = false;
//                    changeAnimation();
//                    mIvBackToTop.setVisibility(View.VISIBLE);
//                } else if (scrollY < 405 && flagUp && (mSearchbar.getVisibility() == View.GONE)) {
//                    flagUp = false;
//                    flagDown = true;
//                    //
//                    setAnimationflag = true;
//                    changeAnimation();
//                    mIvBackToTop.setVisibility(View.GONE);
//                }
////
////                if (scrollY > UIUtils.dip2px(600)) {
////
////                } else {
////
////                }
//
//            } else {
//                lastScrollY = -1;
//            }
//            //此时的距离和记录下的距离不相等，在隔5毫秒给handler发送消息
//            if (lastScrollY != scrollY) {
//                lastScrollY = scrollY;
//
//                handler.sendMessageDelayed(handler.obtainMessage(), 100);
//            }
//            if (mPullToRefreshListView.getScrollY() < 0) {
//                scrollY = 0;
//            }
        }
    };

    private void initFloatingActionButton() {
        mFab = (ImageView) mParentView.findViewById(R.id.fab);
    }

    private void initListener() {
        mCartProductContainer.setOnClickListener(this);
        mPullToRefreshListView.setSearchbarAlpha(this);
        mHomepage_searchbar.setOnClickListener(this);
        mFab.setOnClickListener(this);
        rlyt_limitimeshop.setOnClickListener(this);
        mDinDanContainer.setOnClickListener(this);
        homepage_iv_refresh.setOnClickListener(this);
        mIvBackToTop.setOnClickListener(this);
    }

    //  private int mCurrenSortIndex;
    public static final int DINDAN = 1;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case DINDAN:
                recevierFromNet();
                break;

        }
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.homepage_cartProduct_container:
                //跳转进购物车
                Intent intent1 = new Intent(getActivity(), ShoppingCartAtc.class);
                intent1.putExtra(ShoppingCartFragment.TYPETITLE, 1);
                showActivity(getActivity(), intent1);
                return;
            case R.id.iv_back_to_top:
                //setListViewPos(0);
                if (mPullToRefreshListView != null) {
                    if (mRefreshableView != null) {
                        if (!(mRefreshableView).isStackFromBottom()) {
                            mRefreshableView.setStackFromBottom(true);
                        }
                        mRefreshableView.setStackFromBottom(false);
                    }
//
//                    //瞬间上滑，需要加载一下动画。
//                   // handler.sendMessageDelayed(handler.obtainMessage(), 100);
                }
                ;
                //置顶

                return;
            case R.id.homepage_rl_dindan_container:
                Intent intent = new Intent(getActivity(), DindanActivity.class);
                startActivityForResult(intent, DINDAN);
                return;
            case R.id.homepage_iv_one:
                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                //EventBus.getDefault().post(new CallMainPagerChangeEvent(1));
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(0).getId());
                return;
            case R.id.homepage_iv_two:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(4).getId());
                return;
            case R.id.homepage_iv_three:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(1).getId());
                return;
            case R.id.homepage_iv_four:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(5).getId());
                return;
            case R.id.homepage_iv_five:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(2).getId());
                return;
            case R.id.homepage_iv_six:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(6).getId());
                return;
            case R.id.homepage_iv_seven:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(3).getId());
                return;
            case R.id.homepage_iv_eight:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(7).getId());
                return;
            case R.id.homepage_iv_nine:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(8).getId());
                return;
            case R.id.homepage_iv_ten:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(12).getId());
                return;
            case R.id.homepage_iv_eleven:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(9).getId());
                return;
            case R.id.homepage_iv_twelve:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(13).getId());
                return;
            case R.id.homepage_iv_thirteen:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(10).getId());
                return;
            case R.id.homepage_iv_fourteen:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(14).getId());
                return;
            case R.id.homepage_iv_fifteen:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(11).getId());
                return;
            case R.id.homepage_iv_sixteen:

                mMainActivity.pager.setCurrentItem(1);
                mMainActivity.onPageSelected(1);
                mMainActivity.setNearByTransfer(mHomePageIconInfoLists.get(15).getId());
                return;
            case R.id.rlyt_limitimeshop://限时抢购
                Intent limitIntent = new Intent(getActivity(), ProductDetailsActivity1.class);
                limitIntent.putExtra(ProductDetailsActivity1.PRODUCT_ID, mLitmit.getBuyLimitID());
                showActivity(getActivity(), limitIntent);
                return;
            case R.id.homepage_iv_refresh:
                //Todo
                Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.homepage_refresh_rotation);
                LinearInterpolator lir = new LinearInterpolator();
                animation.setInterpolator(lir);
                homepage_iv_refresh.startAnimation(animation);
                startLocation();
                //刷新数据；
                getLatestNearByData();
                return;
            case R.id.homepage_searchbar:
                Bundle bundle = new Bundle();
                bundle.putInt(SearchActivity.SEARCHCHOOSE_ID, 0);
                showActivity(getActivity(), SearchActivity.class, bundle);
                return;

            case R.id.fab:
                Bundle bundle2 = new Bundle();
                bundle2.putInt(SearchActivity.SEARCHCHOOSE_ID, 0);
                showActivity(getActivity(), SearchActivity.class, bundle2);
                return;
        }
    }

    private void setListViewPos(int pos) {
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            mPullToRefreshListView.getRefreshableView().smoothScrollToPosition(pos);
        } else {
            mPullToRefreshListView.getRefreshableView().setSelection(pos);
        }
    }

    public void stopRefresh() {
        if (homepage_iv_refresh == null || homepage_iv_refresh.getAnimation() == null) {
            return;
        }
        homepage_iv_refresh.clearAnimation();
    }

    private void initHomePageIconViewPage() {
        mHomepageIconAdapter = new MyPagerAdapter();
        mIconViewPger.setAdapter(mHomepageIconAdapter);
        mIconViewPger.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mIconDotContainer.setBackgroundResource(R.mipmap.homepage_selectdot2);
                    //todo
                } else {
                    mIconDotContainer.setBackgroundResource(R.mipmap.homepage_selectdot1);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        AppIconFromNet();
    }

    private void initHomePageIconInfoDatas() {
        mHomepageIconAdapter = new MyPagerAdapter();
        mIconViewPger.setAdapter(mHomepageIconAdapter);

    }

    private void AppIconFromNet() {
        ///Home/AppIcon
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        //ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));
        FormResultRequest<ArrayList<HomePageIconInfo>> loginRequest = new FormResultRequest(UrlConstants.HOMEAPPICON,
                getHomeAppIcon, this,
                new TypeToken<RequestResult<ArrayList<HomePageIconInfo>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        executeRequest(loginRequest);

    }

    @Override
    public void getLatestAddress(String latestAddress) {
        homepage_tv_refresh_position.setText(latestAddress);
    }


    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = null;
            switch (position) {
                case 0:
                    view = View.inflate(getActivity(), R.layout.item_icon_one, null);
                    if (mHomePageIconInfoLists.size() == 0) {
                        break;
                    }
                    ImageView iv1 = (ImageView) view.findViewById(R.id.homepage_iv_one);
                    ImageView iv2 = (ImageView) view.findViewById(R.id.homepage_iv_two);
                    ImageView iv3 = (ImageView) view.findViewById(R.id.homepage_iv_three);
                    ImageView iv4 = (ImageView) view.findViewById(R.id.homepage_iv_four);
                    ImageView iv5 = (ImageView) view.findViewById(R.id.homepage_iv_five);
                    ImageView iv6 = (ImageView) view.findViewById(R.id.homepage_iv_six);
                    ImageView iv7 = (ImageView) view.findViewById(R.id.homepage_iv_seven);
                    ImageView iv8 = (ImageView) view.findViewById(R.id.homepage_iv_eight);
                    iv1.setOnClickListener(HomePageFragment.this);
                    iv2.setOnClickListener(HomePageFragment.this);
                    iv3.setOnClickListener(HomePageFragment.this);
                    iv4.setOnClickListener(HomePageFragment.this);
                    iv5.setOnClickListener(HomePageFragment.this);
                    iv6.setOnClickListener(HomePageFragment.this);
                    iv7.setOnClickListener(HomePageFragment.this);
                    iv8.setOnClickListener(HomePageFragment.this);
                    ArrayList<ImageView> templist = new ArrayList<>();
                    templist.add(iv1);
                    templist.add(iv3);
                    templist.add(iv5);
                    templist.add(iv7);
                    templist.add(iv2);
                    templist.add(iv4);
                    templist.add(iv6);
                    templist.add(iv8);
                    for (int i = 0; i < 8; i++) {
                        if (i <= mHomePageIconInfoLists.size() - 1) {
                            templist.get(i).setVisibility(View.VISIBLE);
                            if (!TextUtils.isEmpty(mHomePageIconInfoLists.get(i).getIconImage())) {
                                GlobalApp.loadImg(templist.get(i), mHomePageIconInfoLists.get(i).getIconImage());
                            }

                        } else {
                            templist.get(i).setVisibility(View.GONE);
                        }
                    }
                    TextView tv1 = (TextView) view.findViewById(R.id.homepage_tv_one);
                    TextView tv2 = (TextView) view.findViewById(R.id.homepage_tv_two);
                    TextView tv3 = (TextView) view.findViewById(R.id.homepage_tv_three);
                    TextView tv4 = (TextView) view.findViewById(R.id.homepage_tv_four);
                    TextView tv5 = (TextView) view.findViewById(R.id.homepage_tv_five);
                    TextView tv6 = (TextView) view.findViewById(R.id.homepage_tv_six);
                    TextView tv7 = (TextView) view.findViewById(R.id.homepage_tv_seven);
                    TextView tv8 = (TextView) view.findViewById(R.id.homepage_tv_eight);
                    templist = null;
                    ArrayList<TextView> templist2 = new ArrayList<>();
                    templist2.add(tv1);
                    templist2.add(tv3);
                    templist2.add(tv5);
                    templist2.add(tv7);
                    templist2.add(tv2);
                    templist2.add(tv4);
                    templist2.add(tv6);
                    templist2.add(tv8);
                    for (int i = 0; i < 8; i++) {
                        if (i <= mHomePageIconInfoLists.size() - 1) {
                            templist2.get(i).setVisibility(View.VISIBLE);
                            templist2.get(i).setText(mHomePageIconInfoLists.get(i).getIconName());
                        } else {
                            templist2.get(i).setVisibility(View.GONE);
                        }
                    }
                    templist2 = null;

                    break;
                case 1:
                    view = View.inflate(getActivity(), R.layout.item_icon_two, null);
                    if (mHomePageIconInfoLists.size() < 8) {
                        break;
                    }
                    ImageView iv9 = (ImageView) view.findViewById(R.id.homepage_iv_nine);
                    ImageView iv10 = (ImageView) view.findViewById(R.id.homepage_iv_ten);
                    ImageView iv11 = (ImageView) view.findViewById(R.id.homepage_iv_eleven);
                    ImageView iv12 = (ImageView) view.findViewById(R.id.homepage_iv_twelve);
                    ImageView iv13 = (ImageView) view.findViewById(R.id.homepage_iv_thirteen);
                    ImageView iv14 = (ImageView) view.findViewById(R.id.homepage_iv_fourteen);
                    ImageView iv15 = (ImageView) view.findViewById(R.id.homepage_iv_fifteen);
                    ImageView iv16 = (ImageView) view.findViewById(R.id.homepage_iv_sixteen);
                    iv9.setOnClickListener(HomePageFragment.this);
                    iv10.setOnClickListener(HomePageFragment.this);
                    iv11.setOnClickListener(HomePageFragment.this);
                    iv12.setOnClickListener(HomePageFragment.this);
                    iv13.setOnClickListener(HomePageFragment.this);
                    iv14.setOnClickListener(HomePageFragment.this);
                    iv15.setOnClickListener(HomePageFragment.this);
                    iv16.setOnClickListener(HomePageFragment.this);

                    ArrayList<ImageView> templist3 = new ArrayList<>();
                    templist3.add(iv9);
                    templist3.add(iv11);
                    templist3.add(iv13);
                    templist3.add(iv15);
                    templist3.add(iv10);
                    templist3.add(iv12);
                    templist3.add(iv14);
                    templist3.add(iv16);


                    for (int i = 0; i < 8; i++) {
                        if (i <= mHomePageIconInfoLists.size() - 8 - 1) {
                            templist3.get(i).setVisibility(View.VISIBLE);
                            if (!TextUtils.isEmpty(mHomePageIconInfoLists.get(i + 8).getIconImage())) {
                                GlobalApp.loadImg(templist3.get(i), mHomePageIconInfoLists.get(i + 8).getIconImage());
                            }
                        } else {
                            templist3.get(i).setVisibility(View.GONE);
                        }
                    }


                    TextView tv9 = (TextView) view.findViewById(R.id.homepage_tv_nine);
                    TextView tv10 = (TextView) view.findViewById(R.id.homepage_tv_ten);
                    TextView tv11 = (TextView) view.findViewById(R.id.homepage_tv_eleven);
                    TextView tv12 = (TextView) view.findViewById(R.id.homepage_tv_twelve);
                    TextView tv13 = (TextView) view.findViewById(R.id.homepage_tv_thirteen);
                    TextView tv14 = (TextView) view.findViewById(R.id.homepage_tv_fourteen);
                    TextView tv15 = (TextView) view.findViewById(R.id.homepage_tv_fifteen);
                    TextView tv16 = (TextView) view.findViewById(R.id.homepage_tv_sixteen);
                    templist3 = null;
                    ArrayList<TextView> templist4 = new ArrayList<>();
                    templist4.add(tv9);
                    templist4.add(tv11);
                    templist4.add(tv13);
                    templist4.add(tv15);
                    templist4.add(tv10);
                    templist4.add(tv12);
                    templist4.add(tv14);
                    templist4.add(tv16);


                    for (int i = 0; i < 8; i++) {
                        if (i <= mHomePageIconInfoLists.size() - 8 - 1) {
                            templist4.get(i).setVisibility(View.VISIBLE);
                            templist4.get(i).setText(mHomePageIconInfoLists.get(i + 8).getIconName());
                        } else {
                            templist4.get(i).setVisibility(View.GONE);
                        }
                    }
                    templist4 = null;
                    break;
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object instanceof View) {
                container.removeView((View) object);
            }
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

    }

    /*初始化轮播图*/
    private void initAutoScrollViewPage() {
        mAutoScrollViewPager = (AutoScrollViewPager<AdvertisementInfo>) mHeadView.findViewById(R.id.autoviewpage_ad);
        mHomePageScrollViewPageContainer = (LinearLayout) (mParentView.findViewById(R.id.advertisement_dotLl));

        mCoverIv = (ImageView) mHeadView.findViewById(R.id.cover_iv);
        mAutoScrollViewPager.setScaleType(ImageView.ScaleType.FIT_XY);
        mAutoScrollViewPager.setClickable(true);
        //加载默认图片
        mAutoScrollViewPager.setImageOptions(new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.morenpic
        )
                .showImageForEmptyUri(R.mipmap.morenpic).showImageOnFail(R.mipmap.morenpic)
                .cacheInMemory(true)// 开启内存缓存
                .cacheOnDisk(true) // 开启硬盘缓存
                .resetViewBeforeLoading(false).build());

        mAutoScrollViewPager.setOnPageItemClickListener(new AutoScrollViewPager
                .OnPageItemClickListener<AdvertisementInfo>() {
            @Override
            public void onPageItemClickListener(AdvertisementInfo pd) {
                switch (pd.getBannerType()) {
                    //    int	bannerType: 链接类型，0外链，1商品，2商家
                    case "0":
                        intentWebView(pd.getBannerUrl(), pd.getBannerName());
                        break;

                    case "1":
                        //ToDo
                        if (TextUtils.isEmpty(pd.getProductId())) {
                            return;
                        }
                        //showToastMsg("跳转到商品页" + pd.getBannerName());
                        Intent intent = new Intent(getActivity(), ProductDetailsActivity1.class);
                        intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, pd.getProductId());
                        intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, pd.getImageUrl());
                        showActivity(getActivity(), intent);

                        break;
                    case "2":
                        //ToDo
                        if (TextUtils.isEmpty(pd.getProductId())) {
                            return;
                        }
                        Intent intent2 = new Intent(getActivity(), MerchantDetailActivity.class);
                        intent2.putExtra(MerchantDetailActivity.Merchant_ID, pd.getBannerId());
                        showActivity(getActivity(), intent2);
                        // showToastMsg("跳转到商家页" + pd.getBannerName());
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageItemClickListener(List<AdvertisementInfo> pagerData, int position) {
            }

        });

        //设置轮播图的宽高

        //338*640
        int width = UIUtils.getDisplayMetrics().widthPixels;

        Float height = (width / 640f) * 338f;

        ViewGroup.LayoutParams layoutParams1 = mAutoScrollViewPager.getLayoutParams();
        layoutParams1.width = width;
        layoutParams1.height = Math.round(height);
        mAutoScrollViewPager.setLayoutParams(layoutParams1);
        AdvertisementFromNet();
    }

    public void intentWebView(String url, String name) {
        Intent intent = new Intent(getActivity(), BaseWebViewAct.class);
        intent.putExtra(BaseWebViewAct.PAGE_URL, url);
        intent.putExtra(BaseWebViewAct.PAGE_TITLE, name);
        startActivity(intent);
    }

    private void initAdvertisementInfoDatas() {
        mCoverIv.setVisibility(View.GONE);
        mAutoScrollViewPager.refreshDatas(mAdvertisementInfoLists, mHomePageScrollViewPageContainer, false, true);
        mAutoScrollViewPager.start(3000);
    }

    //轮播图访问网络
    private void AdvertisementFromNet() {
        //Home/BannerList
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        //ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));
        FormResultRequest<ArrayList<AdvertisementInfo>> loginRequest = new FormResultRequest(UrlConstants
                .HOMEBANNERLIST, getAdvertimentInfo, this,
                new TypeToken<RequestResult<ArrayList<AdvertisementInfo>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);

        executeRequest(loginRequest);
    }


    private Response.Listener<RequestResult<ArrayList<HomePageIconInfo>>> getHomeAppIcon = new Response
            .Listener<RequestResult<ArrayList<HomePageIconInfo>>>() {

        @Override
        public void onResponse(RequestResult<ArrayList<HomePageIconInfo>> result) {
            DebugTool.i("HomeAppIcon", "");
            if (result != null && result.flag == 1 && result.getRs().size() > 0) {
                mHomePageIconInfoLists = result.getRs();
                initHomePageIconInfoDatas();
                totalFlag();
            }
        }
    };

    private void totalFlag() {
        mTotalFlag = mTotalFlag << 1;
        //showToastMsg(mTotalFlag+".)");
        Log.e("OK", mTotalFlag + "访问接口的数量");
        if (mTotalFlag >= 8) {
            mPullToRefreshListView.onRefreshComplete();
            dismissLoadingDialog();
        }
    }

    private Response.Listener<RequestResult<ArrayList<AdvertisementInfo>>> getAdvertimentInfo = new Response
            .Listener<RequestResult<ArrayList<AdvertisementInfo>>>() {

        @Override
        public void onResponse(RequestResult<ArrayList<AdvertisementInfo>> result) {
            DebugTool.i("Advertiment", "");
            if (result != null && result.flag == 1 && result.getRs().size() > 0) {
                mCoverIv.setVisibility(View.GONE);
                mAdvertisementInfoLists = result.getRs();
                //在图片只有一张的情况下，将点隐藏起来，图片多张，将点显示出来
                initAdvertisementInfoDatas();
                if (mAdvertisementInfoLists.size() == 1) {
                    mHomePageScrollViewPageContainer.removeAllViews();
                }
                totalFlag();
            }
        }
    };

    //默认网络请求异常回调
    @Override
    public void onErrorResponse(VolleyError error) {
        dismissLoadingDialog();
        mPullToRefreshListView.onRefreshComplete();
        String msg = getResources().getString(R.string.error_response);
        if (error instanceof ServerFlagError) {
            msg = ((ServerFlagError) error).result.msg;
        } else {
            try {
                if (error.networkResponse != null && error.networkResponse.data != null)
                    msg = new String(error.networkResponse.data, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        showToastMsg(msg);
        dismissLoadingDialog();
        if (nearbyGrouponAdapter.getCount() <= 0) {
            mNearBy.setVisibility(View.GONE);
        }
    }

    private void startLocation() {
        showLoadingDialog(getString(R.string.common_location_ing));
        gaodeMapHelper = new GaodeMapUtil(getActivity());
        gaodeMapHelper.setmLocationListener(new LocationBean.MyLocationListener() {
            @Override
            public void onLocation(LocationBean locationBean) {
                gaodeMapHelper.stop();
                dismissLoadingDialog();
                if (!TextUtils.isEmpty(locationBean.province)) {
                    mLocationBean = locationBean;
                }
                if (locationBean != null) {
                    GlobalApp.getInstance().updateWithNewLocation(mLocationBean);
                    gMapUtil.getLatestGeoAddress();
                }
            }
        });
        gaodeMapHelper.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (gaodeMapHelper != null) {
            gaodeMapHelper.stop();
        }
    }

}
